// pages/toCity/toCity.js
const app = getApp();
const http = require("../../models/http")
Page({
  data: {
    value:"",
    key:"",
    position:'',
    search:"",//搜索框的值
    arr:[],//搜索到的地点
    visitedCity:[]
  },
  onLoad: function (options) {
    let visitedCity = wx.getStorageSync('visitedCity')
    if(visitedCity){
      this.setData({
        visitedCity,
      })
    }else{
      wx.setStorageSync('visitedCity', [])
    }
    http({
      url:"http://192.168.4.20:8000/city",
      success:res=>{
        this.setData({
          value:res.data.data,
          key:Object.keys(res.data.data.cities)
        })
      }
    })
  },

  goBack(event){
    app.globalData.currentCity = event.currentTarget.dataset.name;
    // 将最近访问添加到缓存中
    let visitedCity = wx.getStorageSync('visitedCity');
    let name = event.currentTarget.dataset.name;
    if(!visitedCity.includes(name)&&name.trim()){
      visitedCity.unshift(name)
    }
    wx.setStorageSync("visitedCity", visitedCity.slice(0,3))
    this.setData({
      visitedCity:visitedCity.slice(0,3)
    })
    wx.navigateBack({
      delta: 1, // 回退前 delta(默认为1) 页面
    })
  },

  // 监听输入框
  onChange(event){
    var arr = [];
    this.setData({
      search:event.detail.trim()                                                                          
    })
    console.log(this.data.search);
    for(var res in this.data.value.cities){
      this.data.value.cities[res].forEach(item=>{
        if(item.name.includes(this.data.search) || item.spell.includes(this.data.search)){
          arr.push(item)
        }
      })
    }
    this.setData({
      arr
    })
  },


  onHide:function(){
    // 生命周期函数--监听页面显示
    console.log("onHide");
    
  },
  onUnload(){
    console.log("onUnload");
  },
})